﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SP = Microsoft.SharePoint.Client;

namespace com.sharepointutils.application.Forms
{
    public partial class WikiForm : Form
    {
        public SharePointConnection Connection { get; set; }

        public WikiForm(SharePointConnection connection)
        {
            InitializeComponent();
            this.Connection = connection;
            lbl_wiki_current.Text = Connection.Label;
        }

        private void btn_wiki_updateReferences_Click(object sender, EventArgs e)
        {
            SP.ListItemCollection collection = SharePointUtilities.getAllListItems(Connection.URL, Connection.List, Connection.Credentials);
            double count = 0;
            double total = collection.Count;

            foreach (SP.ListItem x in collection)
            {
                try
                {
                    String html = x["WikiField"].ToString();
                    html = html.Replace("Edge%20Images", @"edgedoc/Images1");

                    int finish = 0;
                    int href = 0;
                    while (html.Contains("Edge%20Training_Data") && finish != -1 && href != -1)
                    {
                        href = html.IndexOf("src", finish);
                        if (href != -1)
                        {
                            int start = html.IndexOf("\"", href); //html.IndexOf("Edge%20Training_Data");
                            finish = html.IndexOf("\"", start + 1);
                            String replace = html.Substring(start + 1, finish - start - 1);


                            if (replace.Contains("Edge%20Training_Data"))
                            {
                                KeyValuePair<String, byte[]> file = SharePointUtilities.DownloadFile(replace, Connection.Credentials);
                                String newpath = SharePointUtilities.uploadDocument(Connection.URL, Connection.Credentials, "Images", "TrainingImages", file.Key, file.Value, true);
                                html = html.Replace(replace, newpath);
                            }
                        }
                    }

                    Dictionary<String, object> props = new Dictionary<string, object>();
                    props.Add("WikiField", html);
                    SharePointUtilities.updateListItem(Connection.URL, Connection.Credentials, Connection.List, x.Id, props);
                }
                catch (Exception ex)
                {
                    //errorLog.Append("Failed to update:" + x.Id + " Message: " + ex.Message);

                }
                count++;
            }
            //txt_errorLog.Text += Environment.NewLine + errorLog.ToString();
        }
    }
}
